<?php

namespace App\Http\Controllers\Saas;

use App\Http\Config\ErrorCode;
use App\Library\TcScfUtil;
use App\Library\Tools;
use App\Models\Saas\Mall;
use App\Models\Saas\Setting;
use App\Models\Saas\UserManager;
use App\Models\User\UserSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class PassportController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ["login", "getConfig", "logout"];
        parent::__construct($request);
    }

    //登陆
    public function login(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if (empty($request["account"])) {
            return $this->return_result(ErrorCode::code("params_not_exist", "账户名"));
        }
        if (empty($request["password"])) {
            return $this->return_result(ErrorCode::code("params_not_exist", "密码"));
        }
        $data = UserManager::query()->where("username", $request["account"])
            ->select(["status", "expired_time", "password", "id"])
            ->first();
        if (!empty($data)) {
            if(!Hash::check($request['password'], $data['password'])){
                return $this->return_result(ErrorCode::code("customized", "密码错误"));
            }
            if($data["id"] != "1" && !empty($data["expired_time"]) && $data["expired_time"] <= time()){
                return $this->return_result(ErrorCode::code('account_expired'));
            }
            if($data["status"] == "3"){
                return $this->return_result(ErrorCode::code('customized', "账号已被删除，请联系管理员"));
            }elseif($data["status"] == "2"){
                $this->returnData = ErrorCode::code('customized', "账号已被禁用");
            }else {
                $userSessionModel = new UserSession();
                $session_id = $userSessionModel->setSession(['saas_id' => $data["id"]]);
                $this->returnData['data'] = ['token' => $session_id];
            }
        } else {
            $this->returnData = ErrorCode::code("customized", "账号不存在");
        }
        return $this->return_result($this->returnData);
    }

    //登录者信息
    public function getInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $data = UserManager::query()->where("id", $this->AU["id"])->first();
        if($data){
            $data = Tools::transferFields($data->toArray());
            if(empty($data["expiredTime"])){
                $data["expiredTime"] = "永久";
            }else{
                $data["expiredTime"] = date("Y-m-d", $data["expiredTime"]);
            }
            $data['avatar'] = !empty($data['avatar']) ? $this->processingPictures($data["avatar"]) : "";
            unset($data['password']);
            $data["createCount"] = Mall::query()->where(["manager_id" => $data["id"]])->count();
            if(!is_numeric($data["appCount"])){
                $data["canCreate"] = "无限制";
            }else{
                $data["canCreate"] = $data["appCount"] - $data["createCount"];
            }
            $tcConfig = Setting::getFields("secret_id,secret_key");
            if(!empty($tcConfig["secretId"]) && !empty($tcConfig["secretKey"])){
                $res = TcScfUtil::getInstance($tcConfig["secretId"], $tcConfig["secretKey"])->describeAccountBalance(); // 余额
                if($res["code"] == "0"){
                    $data["tcAccountInfo"] = ["balance" => $res["data"]["Balance"] / 100, "result" => "获取成功"];
                }else{
                    $data["tcAccountInfo"] = ["balance" => 0, "result" => $res["msg"]];
                }
            }else{
                $data["tcAccountInfo"] = ["balance" => 0, "result" => "未配置腾讯云信息"];
            }
        }
        $data["isSuper"] = $data["id"] == "1" ? true : false;
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    //退出登陆
    public function logout(Request $request)
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $userBaseModel = new UserSession();
        $res = $userBaseModel->sessionDelete($request["token"]);
        if(!$res){
            $returnData['code'] = ErrorCode::$admin_enum['fail'];
            $returnData['msg'] = '注销失败';
            return $returnData;
        }
        return $this->return_result($this->returnData);
    }

    //退出登陆
    public function getConfig()
    {
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = Setting::getFields("logo,site_title,seo_title,copyright");
        if(empty($settingData)){
            foreach (explode(",", "logo,site_title,seo_title,copyright") as $field){
                $settingData[Str::camel($field)] = null;
            }
        }else{
            $settingData["logo"] = $this->processingPictures($settingData["logo"]);
        }
        $this->returnData['data'] = $settingData;
        return $this->return_result($this->returnData);
    }

}